import { createRouter, createWebHashHistory } from 'vue-router';
import LayoutIndex from '@/views/layout/LayoutIndex.vue';

const routes = [
  {
    path: '/',
    redirect: { name: 'UsersIndex' },
  },
  {
    path: '/users',
    name: 'Users',
    redirect: { name: 'UsersIndex' },
    component: LayoutIndex,
    meta: {
      needLogin: true,
    },
    children: [
      {
        path: 'index',
        name: 'UsersIndex',
        component: () => import('@/views/users/UsersIndex.vue'),
        meta: {
          needLogin: true,
        },
      },
      {
        path: 'add',
        name: 'UsersAdd',
        component: () => import('@/views/users/UsersAdd.vue'),
        meta: {
          needLogin: true,
        },
      },
      {
        path: 'edit',
        name: 'UsersEdit',
        component: () => import('@/views/users/UsersEdit.vue'),
        meta: {
          needLogin: true,
        },
      },
      {
        path: 'profile',
        name: 'UsersProfile',
        component: () => import('@/views/users/UsersProfile.vue'),
        meta: {
          needLogin: true,
        },
      },
    ],
  },
  {
    path: '/outlines',
    name: 'Outlines',
    component: LayoutIndex,
    redirect: { name: 'OutlinesIndex' },
    meta: {
      needLogin: true,
    },
    children: [
      {
        path: 'index',
        name: 'OutlinesIndex',
        component: () => import('@/views/outlines/OutlinesIndex.vue'),
        meta: {
          needLogin: true,
        },
      },
    ],
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/LoginIndex.vue'),
  },
  {
    path: '/:match(.*)',
    redirect: { name: 'UsersIndex' },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.meta.needLogin === true) {
    if (localStorage.token === undefined) {
      // 拦截跳转登录页面
      next({ name: 'Login' });
    } else {
      // 需要登录，并且登录
      next();
    }
  } else {
    // needLogin 不存在或者为 false 放行，不需要登录
    next();
  }
});

export default router;
